/*
	Copyright (C) 2013 Pontificia Universidad Catolica del Peru
	contact: http://avatar.inf.pucp.edu.pe/realidad-aumentada/
	address contact: Av. Universitaria 1801, San Miguel, Lima-Peru.
	
	This file is part of UbicAR PUCP.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with This program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
	Authors: Alvaro Roger Agüero Sánchez, Rodolfo Javier Galvez Meza
	Pontificia Universidad Catolica del Peru
	Departamento de Ingeniería
*/

package org.grupoavatar.guiaubicua.auxiliares;

import org.grupoavatar.guiaubicua.VInicial;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {

	  public static final String TABLE_RATING = "ratings";
	  public static final String COLUMN_PUNTO = "punto";
	  public static final String COLUMN_VOTO = "voto";
	
	  private static final String DATABASE_NAME = "ratings.db";
	  private static final int DATABASE_VERSION = 1;
	  private SQLiteDatabase db;
	
	  // Database creation sql statement
	  private static final String DATABASE_CREATE = "create table "
	      + TABLE_RATING + "(" 
		  + COLUMN_PUNTO + " integer not null, " 
	      + COLUMN_VOTO  + " integer not null," 
		  + "primary key ("+COLUMN_PUNTO+","+COLUMN_VOTO+")" +
	      ");";
	
	  public MySQLiteHelper(Context context) {
	    super(context, DATABASE_NAME, null, DATABASE_VERSION);
	  }
	
	  @Override
	  public void onCreate(SQLiteDatabase database) {
	    database.execSQL(DATABASE_CREATE);
	  }
	
	  @Override
	  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	    Log.w(MySQLiteHelper.class.getName(),
	        "Upgrading database from version " + oldVersion + " to "
	            + newVersion + ", which will destroy all old data");
	    db.execSQL("DROP TABLE IF EXISTS " + TABLE_RATING);
	    onCreate(db);
	  }
	
	public boolean addRating(String poi, int rating) {
		// TODO Auto-generated method stub
		try {
			db = this.getWritableDatabase();
			if (votoNoEmitido(poi)) {
				//insert						
			    ContentValues values = new ContentValues();
			    values.put(COLUMN_PUNTO, Integer.parseInt(poi)); // Punto
			    values.put(COLUMN_VOTO, rating); // Votacion
			 
			    // Inserting Row
			    db.insert(TABLE_RATING, null, values);
			    db.close(); // Closing database connection
			    Log.d(VInicial.TAG + "-Rating", "Se insertó el voto con el valor "+String.valueOf(rating));
			    return true;
			} else {
				//update			  
			    ContentValues values = new ContentValues();			
				values.put(COLUMN_VOTO, rating);
				// updating row
				db.update(TABLE_RATING, values, COLUMN_PUNTO + " = ?",
				            new String[] { poi });			
			}
			Log.d(VInicial.TAG + "-Rating", "Se actualizó el voto con el valor "+String.valueOf(rating));
			db.close();
			return false;
		} catch (SQLiteException e) {
			
		} 
		return true;		
	}
	
	public String getVotoAnterior(String poi, int rating) {
		//Si no hay votos antes, devolver "null"
		String nulo = "null";
		SQLiteDatabase db = this.getReadableDatabase();		 
		Cursor cursor = db.query(TABLE_RATING, new String[] { COLUMN_PUNTO, COLUMN_VOTO}, COLUMN_PUNTO + "=?",
				new String[] { poi}, null, null, null, null);
		if (cursor != null) {
			//encontro algo
			if (cursor.moveToFirst()) {
				String resultado;
				resultado = String.valueOf(cursor.getInt(1));
				cursor.close();				
				Log.d(VInicial.TAG + "-Rating", "Se obtuvo un voto anterior con el resultado: "+resultado);
				db.close();
				return resultado;
			} else
			{
				cursor.close();
				Log.d(VInicial.TAG + "-Rating", "Se obtuvo un voto anterior nulo");
				db.close();
				return nulo;
			}
		}	
		db.close();
		return nulo;
	}
	
	private boolean votoNoEmitido(String poi) {
		// TODO Auto-generated method stub		
		SQLiteDatabase db = this.getReadableDatabase();		 
		Cursor cursor = db.query(TABLE_RATING, new String[] { COLUMN_PUNTO, COLUMN_VOTO}, COLUMN_PUNTO + "=?",
				new String[] { poi}, null, null, null, null);
		if (cursor != null) {
			//encontro algo
			if (cursor.moveToFirst()) {
				cursor.close();
				Log.d(VInicial.TAG + "-Rating", "Se emotio un voto antes en este punto");
				return false;
			} else
			{
				cursor.close();
				Log.d(VInicial.TAG + "-Rating", "No se emotio un voto antes en este punto");
				return true;
			}
		}			
		return true;
	}

} 